﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace DATN.mds.Note
{
    public partial class IndexNote : System.Web.UI.Page
    {
        //Biến Toàn Cục để load dữ liệu
        SqlConnection cnn;
        string slala ="";
        
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Us_Id"] != null)
            {
                if (!IsPostBack)
                {
                    DropDownList1.Items.Add("Ba ngày sắp tới");
                    DropDownList1.Items.Add("Ba ngày trước");
                    DropDownList1.Items.Add("Ngày hôm nay");
                    DropDownList1.Items.Add("Tất Cả");
                    DropDownList1.Items.FindByValue("Tất Cả").Selected = true;
                    //Session["Cus_Id"] = "";
                    //Bind data vào GridView
                    slala = "Tất Cả";
                    load_data(slala);

                }
            }
            else
            {
                Response.Redirect("../Account/Login.aspx");
            }

            btnCheckBox.Attributes.Add("onclick", "return confirm('Bạn có chắc chắn xóa không?');");
        }

        //Load Data vao Gridview1
        protected void load_data(string sele)
        {
            try
            {
                cnn = new SqlConnection();
                cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn.Open();
                //DateTimePicker de = new DateTimePicker();
                string query="";
                if (sele == "Ba ngày trước")
                {
                    query = "Select * From Notes Where "
                        + " Us_Id = " + Convert.ToInt32(Session["Us_Id"].ToString()) +
                        "And DATEDIFF(DAY,TimeRemind,GETDATE()) between 1 and 3 Order By TimeRemind";
                }
                else if (sele == "Ngày hôm nay")
                {
                    query = "Select * From Notes Where "
                        + " Us_Id = " + Convert.ToInt32(Session["Us_Id"].ToString()) +
                        " And DATEDIFF(DAY,GETDATE(),TimeRemind) =0 Order By TimeRemind";
                }
                else if (sele == "Ba ngày sắp tới")
                {
                    query = "Select * From Notes Where "
                        + " Us_Id = " + Convert.ToInt32(Session["Us_Id"].ToString()) +
                        " And DATEDIFF(DAY,GETDATE(),TimeRemind) between 0 and 3 Order By TimeRemind";
                }
                else
                {
                    query = "Select * From Notes Where "
                        + " Us_Id = " + Convert.ToInt32(Session["Us_Id"].ToString()) +
                        " And DATEDIFF(DAY,GETDATE(),TimeRemind) >=0 Order By TimeRemind";
                }

                SqlDataAdapter da = new SqlDataAdapter(query, cnn);
                DataSet ds = new DataSet();
                da.Fill(ds, "Notes");

                GridView1.DataSource = ds.Tables["Notes"];
                GridView1.DataBind();
                
                ds.Dispose();
                da.Dispose();
                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi : "+ ex);
            }
        }

     

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                // get the categoryID of the clicked row
                try
                {
                    int No_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["No_Id"] = No_Id.ToString();
                   
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }
            if (e.CommandName == "Edit")
            {
                // get the categoryID of the clicked row
                try
                {
                    int No_Id = Convert.ToInt32(e.CommandArgument);
                    // Create New Session And Redirect to delete page
                    Session["No_Id"] = No_Id.ToString();
                    Response.Redirect("../mds.Note/EditNote.aspx");
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
                }
            }

        }
         
        //Chuyển Sang Trang CreatNew
        protected void Create_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("~/mds.Note/CreateNote.aspx");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn muốn xóa nội dung trong cột này! - " + "')");

                LinkButton l2 = (LinkButton)e.Row.FindControl("LinkButton2");
                l2.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn muốn sửa nội dung trong cột này! - " + "')");
            }
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkBxSelect");
                CheckBox chkBxHeader = (CheckBox)this.GridView1.HeaderRow.FindControl("chkBxHeader");
                HiddenField hdnFldId = (HiddenField)e.Row.Cells[0].FindControl("hdnFldId");

                chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,document.getElementById('{0}'),'{1}');", chkBxHeader.ClientID, hdnFldId.Value.Trim());
            }

            if (e.Row.DataItemIndex == -1)
                return;

            e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
            if ((e.Row.RowIndex % 2) == 0)
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#aafdaa'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#b4cbd5'");
            }
            else
            {
                e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#aafdaa'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            //BindGridControl();
            GridView1.PageIndex = e.NewPageIndex;
            load_data(slala);
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //Int16 nu = Convert.ToInt16(e.RowIndex);
            //Show.Text = GridView1.Rows[nu].Cells[2].Text;
            //string id = GridView1.Rows[nu].Cells[2].Text.ToString();

            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
            string ac = "Delete From Notes Where No_Id =" + Convert.ToInt32(Session["No_Id"].ToString());

            SqlCommand cmd = cnn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = ac;

            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
            load_data(slala);
        }

        //Xóa List Note đã lựa chọn
        protected void btnCheckBox_Click(object sender, EventArgs e)
        {
            //Get Ids
            string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');
            lb_IdCheckBox.Text = "User Id Da checked là:";
            if (IDs.Length > 0)
            {
                for (int i = 0; i < IDs.Length; i++)
                {
                    //Label8.Text += CheckMail(IDs[i]) + ";";
                    //AllMail += CheckMail(IDs[i]) + ",";
                    lb_IdCheckBox.Text += IDs[i] + ";";
                    int id = int.Parse(IDs[i]);
                    DeleteMany(id);
                    
                }
            }
            else
            {
                //Label8.Text = "Bạn Chưa chọn Khách Hàng Nào cả!";
                lb_IdCheckBox.Text = "Bạn Chưa chọn Khách Hàng Nào cả!";
            }
            load_data(slala);
        }

        // Xóa Note
        protected void DeleteMany(int id)
        {
            SqlConnection cnn = new SqlConnection();
            cnn.ConnectionString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
            //int xid = id;
            string com = "Delete From Notes Where No_Id = " + id;

            SqlCommand cmd = cnn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = com;

            cnn.Open();
            cmd.ExecuteNonQuery();
            cnn.Close();
            //load_data();
            //Page.Response.Redirect("~/mds.Note/IndexNote.aspx");

        }

        //protected void SortButton_Click1(object sender, EventArgs e)
        //{
            
        //    string expression;
        //    string direction;
        //    //expression = e.SortExpression;
        //    expression = DropDownList1.SelectedValue;
        //    if (DirectionList.SelectedValue == "Ascending")
        //    {
        //        direction = "ASC";
        //    }
        //    else
        //    {
        //        direction = "DESC";
        //    }

        //    DataTable dataTable = GridView1.DataSource as DataTable;
        //    DataView dataView = new DataView(dataTable);
        //    dataView.Sort = expression + " " + direction;

        //    GridView1.DataSource = dataView;
        //    //GridView1.Sort(expression, direction);
        //    GridView1.DataBind();
                
        //    //GridView1.Sort(expression, direction);
            
        //}

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }

            return newSortDirection;
        }

        protected void SortButton_Click(object sender, GridViewSortEventArgs e)
        {
            if (IsPostBack)
            {
                DataTable dataTable = GridView1.DataSource as DataTable;

                if (dataTable != null)
                {
                    DataView dataView = new DataView(dataTable);
                    dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                    GridView1.DataSource = dataView;
                    GridView1.DataBind();
                }
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            slala = DropDownList1.SelectedValue;
            load_data(slala);

        }


    }
}